package com.softeem.springboot04.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softeem.springboot04.entity.User;
import com.softeem.springboot04.mapper.UserMapper;
import com.softeem.springboot04.service.IUserService;
import com.softeem.springboot04.vo.R;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public R login(User user) {
        QueryWrapper<User> query = Wrappers.query();
        query.eq("username", user.getUsername());
        User user1 = getBaseMapper().selectOne(query);
        if(Objects.isNull(user1)){
            return R.fail().setMsg("用户不存在");
        }
        //将用户输入的密码和查询到的盐组合加密重新设置到输入的密码中
        user.setPassword(SecureUtil.md5(user.getPassword() + user1.getSalt()));
        if(Objects.equals(user.getPassword(),user1.getPassword())){
            return R.ok().setMsg("登录成功").setData(user1);
        }
        return R.fail().setMsg("密码错误");
    }

    @Override
    public R reg(User user) {
        QueryWrapper<User> query = Wrappers.query();
        query.eq("username", user.getUsername());
        boolean exists = getBaseMapper().exists(query);
        if(exists){
            return R.fail().setMsg("该用户已存在");
        }
        String salt = RandomUtil.randomString(6);
        String pwd = SecureUtil.md5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(pwd);
        //执行添加
        if(save(user)){
            return R.ok().setMsg("注册成功").setData(user);
        }
        return R.fail().setData("注册失败");
    }
}
